package org.yray.tts.format;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;

import java.io.IOException;
import java.io.RandomAccessFile;

@Slf4j
public class WavFile  {

    private  RandomAccessFile file;
    private String fileName;

    public WavFile(String fileName,WavHeader header)
    {
        try  {
            file  = new RandomAccessFile(fileName, "rw");
            byte[] h = header.getHeaderByte();
            assert h.length == 44; //WAV标准，头部应该是44字节
            file.write(h);
            this.fileName=fileName;
        }
        catch (Exception e)
        {
            log.error(e.getMessage());
            if(file!=null)
            {
                try {
                    file.close();
                } catch (IOException e1) {
                    log.error(e1.getMessage());
                }

            }
        }
    }

    public void write(byte[] bs)
    {
        try {
            file.write(bs);
        } catch (IOException e) {
            log.error("filename={},Exception:{}",fileName, ExceptionUtils.getStackTrace(e));
            try {
                file.close();
            } catch (IOException e1) {
                log.error("write err:{}", ExceptionUtils.getStackTrace(e1));
            }
        }
    }

    public void writeFileLen(int pcmLen)
    {
        int fileLen=pcmLen+(44 - 8);
        try {
            file.seek(4);
            file.write(WavHeader.intToBytes(fileLen));
            file.seek(40);
            file.write(WavHeader.intToBytes(pcmLen));
        }catch (IOException e1) {
            log.error("Exception:{}", ExceptionUtils.getStackTrace(e1));
        }
    }
    public void close()
    {
        try {
            file.close();
            log.info("save file={},succ",fileName);
        } catch (IOException e1) {
            log.error("Exception:{}", ExceptionUtils.getStackTrace(e1));
        }
    }
}
